import { useUserStore } from '@/store/user';
import { ElNotification } from 'element-plus'
import { reactive } from 'vue'
import dayjs from 'dayjs'

export const NotifyOk = (msg: string = '成功', time: number = 2000) => {
    ElNotification({
        message: msg,
        type: 'success',
        duration: time
    })
}

export const NotifyError = (msg: string = '请求失败', time: number = 2000) => {
    ElNotification({
        message: msg,
        type: 'error',
        duration: time
    })
}

// 根据类型初始化值
export const initByValueType = (val: unknown) => {
    if (typeof val === 'string') {
        return ''
    }
    else if (typeof val === 'number') {
        return 0
    }
    else if (typeof val === 'boolean') {
        return false
    }
    else if (typeof val === 'undefined') {
        return undefined
    }
    else if (val === null) {
        return null
    }
    else if (Array.isArray(val)) {
        return []
    }
    else if (typeof val === 'object') {
        for (const k in (val as Record<PropertyKey, string | number | boolean>))
            (val as any)[k] = initByValueType((val as Record<PropertyKey, string | number | boolean>)[k])

        return val
    }
    else {
        return undefined
    }
}

/**
 * 初始化响应式对象
 * @param dataObj 数据对象
 * @param keys 操作得key值
 * @param isDelete 是否为删除还是保留上面得keys值
 * 如果为false，那么对象只会剩下keys中得属性，并完成初始化
 */
export const initReactive = (dataObj: Record<string, any>, keys?: Array<keyof typeof dataObj>, isDelete = true) => {
    const dataObjKeys = Object.keys(dataObj || {})
    if (dataObjKeys.length > 0) {
        dataObjKeys.forEach((key) => {
            if (isDelete) {
                if (keys?.includes(key))
                    delete dataObj[key]
                else
                    dataObj[key] = initByValueType(dataObj[key])
                // dataObj[key] = ''
            }
            else {
                if (keys?.includes(key)) {
                    // dataObj[key] = ''
                    dataObj[key] = initByValueType(dataObj[key])
                }
                else {
                    delete dataObj[key]
                }
            }
        })
    }
}

/**
* 赋值响应式对象
* @param originObj 原始对象
* @param dataObj 数据对象
* 注意不要使用该方法清空对象，清空整个对象请使用clearReactive
*/
export const setReactive = (originObj: Record<string, any> | {}, dataObj: Record<string, any>) => {
    const keys = Object.keys(dataObj || {})
    const oldKeys = Object.keys(originObj || {})
    if (keys.length > 0) {
        keys.forEach((key) => {
            const newVal = dataObj[key]
            if (typeof newVal === 'object' && newVal !== null && !Array.isArray(newVal)) {
                const obj = reactive({})

                setReactive(obj, newVal);
                (originObj as Record<string, any>)[key] = obj
            }
            else {
                (originObj as Record<string, any>)[key] = dataObj[key]
            }
            // ;(originObj as Record<string, any>)[key] = dataObj[key]
        })

        oldKeys.forEach((oKey) => {
            if (!keys.includes(oKey))
                delete (originObj as Record<string, any>)[oKey]
        })
    }
    else {
        originObj = reactive(dataObj)
    }
}
/**
 * 设置本地存储
 * @param key
 * @param value
 */
export const setLocalStorage = (key: string, value: any) => {
    localStorage.setItem(key, JSON.stringify(value))
}


/**
 * 从本地存储取值
 * @param key
 * @returns
 */
export const getLocalStorage = (key: string) => {
    const value = JSON.parse(localStorage.getItem(key) as string)
    if (value) {
        return value;
    } else {
        return null
    }
}

/**
 * 删除本地存储
 * @param key
 */
export const removeLocalStorage = (key: string) => {
    localStorage.removeItem(key)
}

// 万亿以下的数字转中文
export const toChineseNumber = (val:number) => {
    const num = val

    const list = num.toString().replace(/(?=(\d{4})+$)/g, ',').split(',')

    const translate = (val: string) => {
        const data = val.split('')
        const chars = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
        const unit = ['', '十', '百', '千']
        let c = ''
        for (let i = 0; i < data.length; i++) {
            const dlight = chars[parseInt(data[i])]
            if (!(data[i] == '0' && data[i + 1] == '0'))
                c = c + dlight + (dlight != '零' ? unit[data.length - 1 - i] : '')
        }
        if (data[data.length - 1] == '0')
            c = c.slice(0, -1)
        return c
    }
    let sum = ''
    const bigUnit = ['', '万', '亿']
    list.forEach((item, index) => {
        sum = sum + translate(item) + bigUnit[list.length - 1 - index]
    })

    return sum
}

/**
 * 获取面包屑数组
 * @param val 路由路径数组
 * @returns 面包屑数组
 */
export const getBreadList = (val:any[]) => {
    const userStore = useUserStore();
    const find  = userStore.userInfo.menuList.find(item => item.path == val[0].path)
    if(find){
        const child = find.children?.find(item => item.path == val[1].path)
        return [find,child]
    }
    return []
}

// 格式化时间戳，默认为精确到秒
export const formatDate = (timestamp: number, format = 'YYYY-MM-DD HH:mm:ss') => {
    if (!timestamp)
        return ''

    return dayjs(timestamp).format(format)
}

// 深拷贝
export const deepCopy = (value:any) => {
    // 加上map,防止对象属性引用自身，造成无限递归
    const map = new WeakMap()
    const _deepCopy = (value:any) => {
        if(value == null || typeof value !== 'object'){
            return value
        }
        if(map.has(value))
            return map.get(value)
        const result = Array.isArray(value)?[]:{}
        map.set(value,result)
        for (const key in value) {
            (result as Record<string, any>)[key] = _deepCopy(value[key])
        }
        return result
    }
    return _deepCopy(value)
}